#ifndef __CALCULATOR_H__
#define __CALCULATOR_H__

#include "lvgl/lvgl.h"
#include "lvgl/demos/lv_demos.h"
#include "lv_drivers/display/fbdev.h"
#include "lv_drivers/indev/evdev.h"
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include <sys/time.h>

char put[256]       = {0};
lv_obj_t * pm_label = NULL;

/* 计算当前表达式 */
static double calculate_current_expression(void)
{
    if(strlen(put) == 0) return 0;

    char expression[256];
    strcpy(expression, put);

    // 替换运算符
    char * ptr;
    while((ptr = strstr(expression, "x")) != NULL) {
        *ptr = '*';
    }

    double num1 = 0, num2 = 0;
    char op    = '\0';
    int parsed = 0;

    // 解析表达式
    parsed = sscanf(expression, "%lf%c%lf", &num1, &op, &num2);

    if(parsed < 1) return 0;

    if(parsed == 1) {
        return num1;
    } else if(parsed == 3) {
        switch(op) {
            case '+': return num1 + num2;
            case '-': return num1 - num2;
            case '*': return num1 * num2;
            case '/':
                if(num2 != 0)
                    return num1 / num2;
                else
                    return 0;
            default: return num1;
        }
    }

    return 0;
}

/* 检查字符串是否包含运算符 */
static int contains_operator(const char * str)
{
    return strchr(str, '+') != NULL || strchr(str, '-') != NULL || strchr(str, 'x') != NULL || strchr(str, '/') != NULL;
}

/* 统一的点击回调 */
static void btn_click_cb(lv_event_t * e)
{
    const char * txt = lv_event_get_user_data(e);
    printf("按钮: %s\n", txt);

    if(txt == LV_SYMBOL_BACKSPACE) {
        // 退格
        if(strlen(put) > 0) {
            put[strlen(put) - 1] = '\0';
        }
    } else if(!strcmp(txt, "清空")) {
        // 清空
        memset(put, 0, sizeof(put));
    } else if(!strcmp(txt, "=")) {
        // 计算结果并保持结果
        double result = calculate_current_expression();
        snprintf(put, sizeof(put), "%.10g", result);

        // 清理尾随零
        char * dot = strchr(put, '.');
        if(dot) {
            char * p = put + strlen(put) - 1;
            while(p > dot && *p == '0') *p-- = '\0';
            if(p == dot) *dot = '\0';
        }
    } else {
        // 检查是否是运算符
        int is_operator =
            (strcmp(txt, "+") == 0 || strcmp(txt, "-") == 0 || strcmp(txt, "x") == 0 || strcmp(txt, "/") == 0);

        if(is_operator && contains_operator(put)) {
            // 如果当前已经有表达式，先计算再添加新运算符
            double result = calculate_current_expression();

            // 格式化结果并添加新运算符
            snprintf(put, sizeof(put), "%.10g%s", result, txt);

            // 清理尾随零
            char * dot = strchr(put, '.');
            if(dot) {
                char * p = put + strlen(put) - 1;
                while(p > dot && *p == '0') *p-- = '\0';
                if(p == dot) *dot = '\0';
            }
        } else {
            // 普通输入
            // 避免重复运算符
            size_t len = strlen(put);
            if(len > 0) {
                char last_char = put[len - 1];
                int last_is_op = (last_char == '+' || last_char == '-' || last_char == 'x' || last_char == '/');
                int new_is_op  = is_operator;

                if(last_is_op && new_is_op) {
                    // 替换运算符
                    put[len - 1] = txt[0];
                } else {
                    // 正常追加
                    if(len < sizeof(put) - 1) {
                        strcat(put, txt);
                    }
                }
            } else {
                // 第一个字符
                strcpy(put, txt);
            }
        }
    }

    // 更新显示
    lv_label_set_text(pm_label, put);
}

void demo_obj(void)
{

    lv_obj_t * screen = lv_scr_act();
    char * buf[20]    = {
        "7", "8", "9", "/", LV_SYMBOL_BACKSPACE, "4", "5", "6", "x", "^2", "1", "2", "3", "-", "%", "清空",
        "0", ".", "+", "="};
    // 获取当前活动屏幕
    lv_obj_t * pm = lv_obj_create(screen);
    lv_obj_set_size(pm, 800, 120);
    lv_obj_set_pos(pm, 0, 0);
    lv_obj_set_style_radius(pm, 0, 0);
    lv_obj_set_scrollbar_mode(pm, LV_SCROLLBAR_MODE_OFF);
    lv_obj_clear_flag(pm, LV_OBJ_FLAG_SCROLLABLE);
    pm_label = lv_label_create(pm);
    lv_label_set_text(pm_label, put);
    lv_obj_center(pm_label);

    // ========================================
    lv_obj_t * obj = lv_obj_create(screen);
    lv_obj_set_size(obj, 800, 360);
    lv_obj_set_pos(obj, 0, 120);
    lv_obj_set_scrollbar_mode(obj, LV_SCROLLBAR_MODE_OFF);
    lv_obj_clear_flag(obj, LV_OBJ_FLAG_SCROLLABLE);
    lv_obj_set_style_radius(obj, 0, 0);
    for(int i = 0; i < 4; i++) {
        for(int j = 0; j < 5; j++) {
            lv_obj_t * btn = lv_btn_create(obj);
            lv_obj_set_size(btn, 140, 60);
            lv_obj_set_style_radius(btn, 5, 0);
            lv_obj_set_pos(btn, 155 * j, 80 * i);
            lv_obj_t * label = lv_label_create(btn);
            lv_obj_center(label);
            lv_label_set_text(label, buf[i * 5 + j]);
            LV_FONT_DECLARE(lv_font_simsun_16_cjk);
            lv_obj_set_style_text_font(label, &lv_font_simsun_16_cjk, LV_PART_MAIN | LV_STATE_DEFAULT);
            lv_obj_set_style_text_color(label, lv_color_hex(0x000000), LV_PART_MAIN | LV_STATE_DEFAULT);
            lv_obj_add_event_cb(btn, btn_click_cb, LV_EVENT_CLICKED, buf[i * 5 + j]);
            if(!strcmp(buf[i * 5 + j], "^2") || !strcmp(buf[i * 5 + j], "%")) {
                lv_obj_clear_flag(btn, LV_OBJ_FLAG_CLICKABLE);
                lv_obj_set_style_text_color(label, lv_color_hex(0x000000), LV_PART_MAIN | LV_STATE_DEFAULT);
                lv_obj_set_style_bg_color(btn, lv_color_hex(0x808080), 0);
            }
        }
    }
}

#endif

// /* 统一的点击回调 */
// static void btn_click_cb(lv_event_t * e)
// {
//     const char * txt = lv_event_get_user_data(e);
//     printf("param %s\n", txt);
//     if(txt == LV_SYMBOL_BACKSPACE) {
//         if(strlen(put) > 0) {
//             put[strlen(put) - 1] = 0;
//         } else {
//             put[0] = 0;
//         }
//     } else if(!strcmp(txt, "清空")) {
//         memset(put, 0, sizeof(put));
//     } else if(!strcmp(txt, "=")) {

//         strchr(put, '+');
//     } else {
//         strcat(put, txt);
//     }
//     lv_label_set_text(pm_label, put);
// }